﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Threading;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Classes;
using System.ComponentModel;

namespace VAdvantage.Apps
{
    public partial class KPIPane : CFrame
    {
        ViennaRoleCenter rolecenter = null;

        KeyNamePair[] colors = null;

        public KPIPane()
            : base(Msg.GetMsg("AddKPI"))
        {
            InitializeComponent();
            this.SetTitle(Msg.GetMsg("AddKPI"));
            this.Top=120;
            this.Left = 330;
        }

        void SetBusy(bool b)
        {
            SetBusy(false, "");
        }

        void SetBusy(bool b, String t)
        {
            if (b)
            {
                busyWindow.Visibility = System.Windows.Visibility.Visible;
                txtBusy.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                busyWindow.Visibility = System.Windows.Visibility.Collapsed;
            }
            txtBusy.Text = t;

        }


        List<KeyNamePair> _tabList = new List<Model.KeyNamePair>();
        void LoadTabs(List<KeyNamePair> tabList)
        {
            if (tabList.Count <= 0)
            {
                LoadFromDatabase();

            }
            else
            {
                int index = 0;
                for (int i = 0; i <= tabList.Count - 1; i++)
                {
                    cmbTab.Items.Add(tabList[i]);
                    if (rolecenter != null)
                    {

                        if (tabList[i].GetKey() == rolecenter.RC_Tab_ID)
                            index = i;
                    }
                }
                cmbTab.SelectedIndex = index;
            }
        }

        private void LoadFromDatabase()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                string sql = @"
                    SELECT 
                      rct.Name, rct.RC_RoleCenterTab_ID
                    FROM rc_rolecentermanager rcm
                    INNER JOIN rc_rolecentertab rct
                    ON rcm.rc_rolecentermanager_id = rct.rc_rolecentermanager_id 
                    where rcm.IsActive = 'Y' and rcm.ad_role_id = " + Envs.GetCtx().GetAD_Role_ID();

                _tabList.Clear();
                IDataReader dr = DB.ExecuteReader(sql);
                while (dr.Read())
                {
                    KeyNamePair key = new KeyNamePair(int.Parse(dr["RC_RoleCenterTab_ID"].ToString()), dr[0].ToString());
                    Dispatcher.BeginInvoke(() => cmbTab.Items.Add(key));
                }
                dr.Close();
            });
        }


        public KPIPane(ViennaRoleCenter _rolecenter)
            : base(Msg.GetMsg("AddKPI"))
        {
            Utility.Envs.RegisterWindowForm(this);
            rolecenter = _rolecenter;
            InitializeComponent();
            this.Top = 120;
            this.Left = 330;
            SetBusy(true, Msg.GetMsg("Loading"));
           
            LoadDBText();
            if (rolecenter != null)
            {

                LoadTabs(rolecenter.ListTab);
            }
            else
                LoadTabs(new List<KeyNamePair>());
        }


        void LoadDBText()
        {
            lblName.Content = Msg.GetMsg("Name");
            lblTab.Content = Msg.GetMsg("Tab");
            lblBGColor.Content = Msg.GetMsg("BGColor");
            lblSeq.Content = Msg.GetMsg("SeqNo");

            lblColspan.Content = Msg.GetMsg("Colspan");
            lblRowspan.Content = Msg.GetMsg("Rowspan");
            lblDescription.Content = Msg.GetMsg("Description");

            //LoadFramesInCombo();

            SetBusy(false);

            if (rolecenter != null)
            {
                if (rolecenter.EditMode)
                {
                    txtSeq.Text = rolecenter.SeqNo.ToString();
                    txtColspan.Text = rolecenter.Colspan.ToString();
                    txtRowspan.Text = rolecenter.Rowspan.ToString();
                    txtName.Text = rolecenter.PanelName;
                    txtDescription.Text = rolecenter.Description;
                }
            }
        }


        void LoadFramesInCombo()
        {
            SetBusy(true, Msg.GetMsg("Loading"));
            int bgindex = -1;

            ThreadPool.QueueUserWorkItem(delegate
            {

                string sql = "Select AD_PrintColor_ID, Name from AD_PrintColor Where IsActive = 'Y'";
                IDataReader dr = DB.ExecuteReader(sql, null);
                List<KeyNamePair> lColors = new List<KeyNamePair>();
                int counter = 0;
                while (dr.Read())
                {

                    lColors.Add(new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString()));
                    KeyNamePair keys = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());

                    bool pass = false;

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {

                        cmbBGColor.Items.Add(keys);

                        if (rolecenter.EditMode)
                        {
                            if (rolecenter.BGColor_ID.ToString().Equals(keys.GetID()))
                            {
                                bgindex = counter;
                            }
                        }

                        pass = true;

                    });

                    while (!pass)
                        Thread.Sleep(0);

                    pass = false;


                    counter++;
                }
                dr.Close();

                colors = lColors.ToArray();



                if (rolecenter != null)
                {

                    if (rolecenter.EditMode)
                    {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cmbBGColor.SelectedIndex = bgindex);
                    }
                }

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => SetBusy(false));
            });
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            KeyNamePair tabSelected = (KeyNamePair)cmbTab.SelectedItem;
            if (cmbTab.SelectedIndex < 0)
            {
                ShowMessage.Error("SelectTab", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtName.Text))
            {
                ShowMessage.Error("EnterName", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtColspan.Text))
            {
                ShowMessage.Error("EnterColspan", false);
                return;
            }
            //else if (cmbBGColor.SelectedIndex < 0)
            //{
            //    ShowMessage.Error("SelectBGColor", false);
            //    return;
            //}
            else if (string.IsNullOrEmpty(txtRowspan.Text))
            {
                ShowMessage.Error("EnterRowspan", false);
                return;
            }
            else if (string.IsNullOrEmpty(txtSeq.Text))
            {
                ShowMessage.Error("EnterSequence", false);
                return;
            }

            SetBusy(true, "Saving");
            try
            {
                string name = txtName.Text;
                int colspan = int.Parse(txtColspan.Text);
                int rowspan = int.Parse(txtRowspan.Text);
                int seqno = int.Parse(txtSeq.Text);
                string description = txtDescription.Text;
                //int bgcolorid = (cmbBGColor.SelectedItem as KeyNamePair).GetKey();
                KeyNamePair frameSelected = (KeyNamePair)cmbTab.SelectedItem;

                if (colspan > 3)
                    colspan = 3;

                if (colspan <= 0)
                    colspan = 1;

                if (rowspan > 2)
                    rowspan = 2;

                if (rowspan <= 0)
                    rowspan = 1;


                BackgroundWorker bgw = new BackgroundWorker();
                bool b = false;
                bgw.DoWork += (sd, ed) =>
                {
                    int rcpanelid = 0;
                    int id = 0;

                    if (rolecenter != null)
                    {

                        if (rolecenter.EditMode)
                        {
                            rcpanelid = rolecenter.TabPanel_ID;
                            id = rolecenter.KPIPaneID;
                        }
                    }

                    X_RC_KPIPane kpi = new X_RC_KPIPane(Envs.GetCtx(), id, null);
                    kpi.SetName(name);
                    kpi.SetDescription(description);
                    //kpi.SetBG_Color_ID(bgcolorid);
                    kpi.SetSeqNo(seqno);
                    b = kpi.Save();

                    if (b)
                    {
                        rolecenter.Description = description;
                        rolecenter.PanelName = name;
                        rolecenter.SeqNo = seqno;

                        X_RC_TabPanels tabPanel = new X_RC_TabPanels(Envs.GetCtx(), rcpanelid, null);
                        tabPanel.SetRecord_ID(kpi.Get_ID());
                        tabPanel.SetRoleCenterPanels("3");
                        tabPanel.SetColspan(colspan);
                        tabPanel.SetRowspan(rowspan);
                        tabPanel.SetSeqNo(seqno);
                        tabPanel.SetRC_RoleCenterTab_ID(frameSelected.GetKey());

                        b = tabPanel.Save();
                    }
                };

                bgw.RunWorkerCompleted += (sd, ed) =>
                {
                    if (b)
                    {
                        ShowMessage.Info("Saved", false, "", "");
                        if (!rolecenter.EditMode)
                        {
                            cmbTab.SelectedIndex = -1;
                            txtName.Text = "";
                            txtDescription.Text = "";
                            cmbBGColor.SelectedIndex = -1;
                            txtColspan.Text = "";
                            txtRowspan.Text = "";
                            txtSeq.Text = "";
                        }
                    }
                    else
                        ShowMessage.Info("NotSaved", false, "", "");


                    SetBusy(false);
                };

                bgw.RunWorkerAsync();
            }
            catch
            {
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void cmbBGColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
